mini.parse();

var upload;

window.onload = function() {
	upload = new SWFUpload({
	//文件加载上传所执行的URL
	upload_url: __root+"/fileUploadContorller.do?uploadPath="+imgpath,
	//post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},
	
	//文件上传参数设定
	file_size_limit : "100 MB",	// 100MB
	file_types : "*.jpge;*.bmp;*.jpg;*.gif;*.png",
	file_types_description : "All Files",
	file_upload_limit : 20,//上传的文件数目
	file_queue_limit : 0,//0特殊值，表示不限制队列文件数目
	
	//事件句柄设定
	swfupload_preload_handler : preLoad,//准备上传
	swfupload_load_failed_handler : loadFailed,//加载失败
	file_dialog_start_handler : function(){},//浏览文件
	file_queued_handler : fileQueued,//加入上传队列
	file_queue_error_handler : fileQueueError,//加入上传队列错误
	file_dialog_complete_handler : fileDialogComplete,//文件选择完成
	upload_start_handler : uploadStart,//上传开始
	upload_progress_handler : uploadProgress,//上传过程中
	upload_error_handler : uploadError,//上传出错
	upload_success_handler : uploadSuccess,//上传成功
	upload_complete_handler : uploadComplete,//上传完成
	
	// Button Settings
	button_image_url : __root+"/admin/resource/swfrpc/images/uploadPic.jpg",
	button_placeholder_id : "spanButtonPlaceholder",
	button_text : "<span class='redText'>添加文件</span>",
	button_text_style : ".redText { font-size:12px;font-family:宋体;color:#201F35}",
	button_width: 81,
	button_height: 22,
	button_text_left_padding : 25,
	button_text_top_padding : 3,
	// Flash Settings
	flash_url : __root+"/admin/resource/swfrpc/swfupload.swf",
	flash9_url : __root+"/admin/resource/swfrpc/swfupload_fp9.swf",
	
	//自定义的控件获取。
//	custom_settings : {
//		progressTarget : "picUploadGrid"//id号
//	},
	
	// Debug Settings
	debug: false
	});
}

/*
 * 句柄事件的实现方法
 */	
//准备上传
function preLoad() {
	if (!this.support.loading) {
		alert("您需要安装Flash Player9.028或以上版本才能使用上传!");
		return false;
	}
}
//加载失败
function loadFailed() {
	alert("加载文件失败!");
}
//加入上传队列
function fileQueued(file) {
	//var grid=this.customSettings.progressTarget;
	var fileData={
			id : file.id,
			name : file.name,
			size : file.size,
			type : file.type,
			state : file.filestatus,
			percent : 0
		};
	//dataGrid=mini.get(grid);
	dataGrid=mini.get("picUploadGrid");
	dataGrid.addRow(fileData);
}
//加入上传队列错误
function fileQueueError(file, errorCode, message) {
	if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
		MiniuiTools.miniWarning("系统提示","你最多只能一次添加20张图片！");
		return;
	}
	switch (errorCode) {
	case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
		MiniuiTools.miniWarning("系统提示","文件超过最大限制！");
		break;
	case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
		MiniuiTools.miniWarning("系统提示","文件大小为0！");
		break;
	case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		MiniuiTools.miniWarning("系统提示","无效的文件类型！");
		break;
	case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
		MiniuiTools.miniWarning("系统提示","你最多只能一次添加20张图片！");
		break;
	default:
		if (file !== null) {
			progress.setStatus("未知系统错误");
		}
		break;
	}
}
//文件选择完成
function fileDialogComplete(numFilesSelected, numFilesQueued) {
	//注释取消自动上传
	//this.startUpload();
}
//上传开始
function uploadStart(file) {
	//此处创建传递参数的代码post_params
	if (upload) {
		if (upload.getStats().files_queued > 0) {
			upload.uploadStopped = false;
			upload.startUpload();
		}
	}
}
//上传过程中（进度条）
function uploadProgress(file, bytesComplete, totalBytes) {
	var percent = Math.ceil((bytesComplete / totalBytes) * 100);
	percent = percent == 100? 99 : percent;
	var items=mini.get("picUploadGrid").getData();
	for(var i=0;i<items.length;i++){
			if(items[i].id==file.id){
				mini.get("picUploadGrid").updateRow(items[i],{percent:percent});
				mini.get("picUploadGrid").updateRow(items[i],{state:file.filestatus});
			}
		}
}
//上传成功
function uploadSuccess(file, serverData) {
	var items=mini.get("picUploadGrid").getData();
	json=mini.decode(serverData);
	if (json) {
		for(var i=0;i<items.length;i++){
			if(items[i].id==file.id){
				mini.get("picUploadGrid").updateRow(items[i],{state:file.filestatus});
				mini.get("picUploadGrid").updateRow(items[i],{imgPath:json.imgPath});
			}
		}			
	}else{
		for(var i=0;i<items.length;i++){
			if(items[i].id==file.id){
				mini.get("picUploadGrid").updateRow(items[i],{percent:"0"});
				mini.get("picUploadGrid").updateRow(items[i],{state:"-3"});
			}
		}
	}
}
//文件上传完成，进行下一个文件的上传
function uploadComplete(file) {
	var items=mini.get("picUploadGrid").getData();
	if(file.filestatus==-4){
		for(var i=0;i<items.length;i++){
			if(items[i].id==file.id){
			    mini.get("picUploadGrid").updateRow(items[i],{percent:"100"});
				if(items[i].state!=-3){
				    mini.get("picUploadGrid").updateRow(items[i],{state:file.filestatus});
				}
			}
		}
	}
	if (upload.getStats().files_queued > 0 && upload.uploadStopped == false) {
		upload.startUpload();
	}else{
		var fileNames = "";
		for ( var i = 0; i < items.length - 1; i++){
			fileNames += items[i].imgPath+ ",";
		}
		if(items.length!=0)
		fileNames += items[items.length - 1].imgPath;
		$.ajax({
		        url: __root + "/uploadGoodsPic.do",
		        data : {
		  			fileNames : fileNames,
		  			bgiId : bgiId
		  		},
		        success: function (text) {
		       		MiniuiTools.miniInfo("系统提示","文件上传完成！", function(){
        			});
                },
                error: function (jqXHR, textStatus, errorThrown) {
        			MiniuiTools.miniError("系统提示","保存数据库失败！");
                    }
                });			
	}		
}
//上传错误
function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("上传错误: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			progress.setStatus("Configuration Error");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("上传失败");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("安全性错误");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("超过上传限制");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			progress.setStatus("文件没有找到");
			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("验证失败，上传跳过");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("取消");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("停止");
			break;
		default:
			progress.setStatus("未知错误: " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}


//点击上传时
function picStartUpload(){
	upload.startUpload();
}
//停止上传
function picStopUpload(){
	if (upload) {
		upload.uploadStopped = true;
		upload.stopUpload();
	}
}
/*
 * grid渲染，根据SwpUpload各个状态标志，对应文件状态
 */
function onStateRender(e) {
    var n = parseInt(e.row.state);
    switch(n){
		case -1 : return '未上传';
		break;
		case -2 : return '正在上传';
		break;
		case -3 : return '<div style="color:red;">上传失败</div>';
		break;
		case -4 : return '上传成功';
		break;
		case -5 : return '取消上传';
		break;
		default: return "";
	}
} 
function onSizeRender(e) {
	var bytes = parseInt(e.row.size);
	var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
	var m = Math.floor(Math.log(bytes)/Math.log(1024));
	return (bytes/Math.pow(1024, Math.floor(m))).toFixed(2)+" "+s[m];
}

function onPercentRender(e) {
	var v=e.row.percent;
	var progressBarTmp = getTplStr(v);
    return progressBarTmp;
}
function getTplStr(v){
	var bgColor = "orange";
	var borderColor = "#008000";
	return String.format(
			'<div>'+
				'<div style="border:1px solid {0};height:10px;width:{1}px;margin:4px 0px 1px 0px;float:left;">'+		
					'<div style="float:left;background:{2};width:{3}%;height:10px;"><div></div></div>'+
				'</div>'+
			'<div style="text-align:center;float:right;width:40px;margin:3px 0px 1px 0px;height:10px;font-size:12px;">{3}%</div>'+			
		'</div>', borderColor,(90),bgColor, v);
}
function onActionRender(e) {
	var id=e.row.id;
	var s = '<a class="New_Button" href="javascript:void(0);" onclick="onDelete(\''+id+'\')">移除</a>';
	return s;
}
function onDelete(id) {
	upload.cancelUpload(id,false);
	var item=mini.get("picUploadGrid").getSelected();
	mini.get("picUploadGrid").removeRow(item);
	 
}
function deleteAll() {
	var items=mini.get("picUploadGrid").getData();
	for (var i = items.length - 1; i >= 0; i-- ) {
		upload.cancelUpload(items[i].id,false);
	}
	mini.get("picUploadGrid").removeRows(items);
	upload.uploadStopeed = false;
}